package com.system.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.user.dao.BindDao;
import com.system.user.dao.GasDao;
import com.system.user.dao.ThresholdDao;
import com.system.user.entity.GasEntity;
import com.system.user.entityVO.GasVO;
import com.system.user.service.GasService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("gasService")
public class GasServiceImpl implements GasService {

    @Autowired
    private GasDao gasDao;

    @Autowired
    private ThresholdDao thresholdDao;

    @Autowired
    private BindDao bindDao;

    @Override
    public List<GasEntity> findAll() {
        return gasDao.selectAll();
    }

    @Override
    public List<GasEntity> findBySiteOrNumber(GasEntity gasEntity) {
        return gasDao.selectBySiteOrNumber(gasEntity);
    }

    @Override
    public List<GasVO> selectByUid(Integer uId, Integer number) {
        return gasDao.selectByUid(uId, number);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(GasEntity gas) throws Exception {
        if (gasDao.insertGas(gas) > 0) {
            gas.setGasNumber("g" + gas.getId());
            if (gasDao.updateGas(gas) > 0) {
                if (thresholdDao.insertThreshold(gas.getGasNumber(), null) > 0) {
                    return true;
                }
            }
        }
        throw new Exception();
    }

    @Override
    public boolean update(GasEntity gas) {
        if (gasDao.updateGas(gas) > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer id) {
        GasEntity gas = gasDao.selectById(id);
        if (gasDao.deleteGas(id) > 0) {
            if (thresholdDao.deleteThreshold(gas.getGasNumber()) > 0) {
                bindDao.deleteBindByBNumber(gas.getGasNumber());
                return true;
            }
        }
        return false;
    }
}
